<template>
	<view class="page-container">
	<view class="container">
		<!-- 自定义导航栏 -->
		<CustomNavbar title="账户管理" />
		
		<!-- 账户列表 -->
		<view class="accounts-section">
			<view class="section-header">
				<text class="section-title">我的账户</text>
				<view class="add-account-btn" @click="showAddModal">
					<text class="add-icon">+</text>
					<text class="add-text">添加账户</text>
				</view>
			</view>
			
			<view class="accounts-list">
				<view 
					v-for="account in accounts" 
					:key="account.id"
					class="account-item"
					@click="editAccount(account)"
				>
					<view class="account-info">
						<text class="account-icon">{{account.icon}}</text>
						<view class="account-details">
							<text class="account-name">{{account.name}}</text>
							<text class="account-type">{{getAccountTypeText(account.accountType)}}</text>
						</view>
					</view>
					<view class="account-balance">
						<text class="balance-amount">¥{{account.currentBalance}}</text>
						<view class="account-actions">
							<view class="action-btn history" @click.stop="viewAccountHistory(account)">
								<text class="action-icon">📊</text>
							</view>
							<view class="action-btn edit" @click.stop="editAccount(account)">
								<text class="action-icon">✏️</text>
							</view>
							<view 
								v-if="account.accountType !== 'NOT_COUNTED'"
								class="action-btn delete" 
								@click.stop="confirmDelete(account)"
							>
								<text class="action-icon">🗑️</text>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 空状态 -->
				<view v-if="accounts.length === 0 && !loading" class="empty-state">
					<view class="empty-icon">💳</view>
					<text class="empty-text">还没有账户</text>
					<text class="empty-desc">点击添加按钮创建您的第一个账户</text>
				</view>
			</view>
		</view>
		
		<!-- 总资产统计 -->
		<view class="summary-section">
			<view class="summary-item">
				<text class="summary-label">总资产</text>
				<text class="summary-amount">¥{{totalBalance}}</text>
			</view>
		</view>
	</view>
	
	<!-- 账户编辑弹窗 -->
	<view v-if="modalVisible" class="modal-overlay" @click="hideModal">
		<view class="modal-content" @click.stop>
			<view class="modal-header">
				<text class="modal-title">{{isEdit ? '编辑账户' : '添加账户'}}</text>
				<view class="close-btn" @click="hideModal">
					<text class="close-icon">×</text>
				</view>
			</view>
			
			<view class="modal-body">
				<!-- 账户名称 -->
				<view class="form-item">
					<text class="form-label">账户名称</text>
					<input 
						class="form-input" 
						v-model="formData.name" 
						placeholder="请输入账户名称"
						maxlength="20"
					/>
				</view>
				
				<!-- 账户类型 -->
				<view class="form-item">
					<text class="form-label">账户类型</text>
					<view class="account-types">
						<view 
							v-for="type in accountTypes" 
							:key="type.value"
							:class="['type-option', formData.accountType === type.value ? 'active' : '']"
							@click="selectAccountType(type.value)"
						>
							<text class="type-icon">{{type.icon}}</text>
							<text class="type-name">{{type.name}}</text>
						</view>
					</view>
				</view>
				
				<!-- 账户图标 -->
				<view class="form-item">
					<text class="form-label">账户图标</text>
					<view class="icon-selector">
						<view 
							v-for="icon in accountIcons" 
							:key="icon"
							:class="['icon-option', formData.icon === icon ? 'active' : '']"
							@click="selectIcon(icon)"
						>
							<text class="icon-text">{{icon}}</text>
						</view>
					</view>
				</view>
				
				<!-- 初始余额 -->
				<view class="form-item">
					<text class="form-label">{{isEdit ? '当前余额' : '初始余额'}}</text>
					<input 
						class="form-input" 
						v-model="formData.balance" 
						type="digit"
						placeholder="0.00"
					/>
				</view>
				
				<!-- 账户描述 -->
				<view class="form-item">
					<text class="form-label">账户描述</text>
					<input 
						class="form-input" 
						v-model="formData.description" 
						placeholder="账户描述（可选）"
						maxlength="50"
					/>
				</view>
				
				<!-- 是否计入总资产 -->
				<view class="form-item">
					<view class="checkbox-item" @click="toggleIncludeInTotal">
						<view :class="['checkbox', formData.includeInTotal ? 'checked' : '']">
							<text v-if="formData.includeInTotal" class="check-icon">✓</text>
						</view>
						<text class="checkbox-label">计入总资产</text>
					</view>
				</view>
			</view>
			
			<view class="modal-footer">
				<view class="btn-cancel" @click="hideModal">取消</view>
				<view class="btn-save" @click="saveAccount">{{isEdit ? '保存' : '创建'}}</view>
			</view>
		</view>
	</view>
	</view>
</template>

<script>
	import { accountAPI, apiUtils } from '@/utils/api.js'
	import CustomNavbar from '@/components/CustomNavbar.vue'
	
	export default {
		components: {
			CustomNavbar
		},
		data() {
			return {
				accounts: [],
				totalBalance: 0,
				loading: false,
				modalVisible: false,
				isEdit: false,
				editAccountId: null,
				formData: {
					name: '',
					accountType: 'CASH',
					icon: '💰',
					balance: '',
					description: '',
					includeInTotal: true
				},
				accountTypes: [
					{ value: 'CASH', name: '现金', icon: '💰' },
					{ value: 'BANK_CARD', name: '银行卡', icon: '🏦' },
					{ value: 'CREDIT_CARD', name: '信用卡', icon: '💳' },
					{ value: 'ALIPAY', name: '支付宝', icon: '💙' },
					{ value: 'WECHAT', name: '微信', icon: '💚' },
					{ value: 'OTHER', name: '其他', icon: '📱' }
				],
				accountIcons: ['💰', '🏦', '💳', '💙', '💚', '📱', '💎', '🎯', '⭐', '🔥', '💫', '🌟']
			}
		},
		onLoad() {
			// 检查登录状态
			if (!apiUtils.isLoggedIn()) {
				uni.reLaunch({
					url: '/pages/login/login'
				});
				return;
			}
			
			this.loadAccounts()
			this.loadTotalBalance()
		},
		methods: {
		async loadAccounts() {
			try {
				this.loading = true
				console.log('开始加载账户列表...')
				
				// 检查登录状态
				const token = uni.getStorageSync('token')
				console.log('当前token:', token ? token.substring(0, 20) + '...' : 'null')
				
				if (!token) {
					console.error('没有找到token，跳转登录页面')
					uni.reLaunch({
						url: '/pages/login/login'
					})
					return
				}
				
				const accounts = await accountAPI.getAllAccounts()
				console.log('获取到账户数据:', accounts)
				this.accounts = accounts.filter(account => account.accountType !== 'NOT_COUNTED')
				console.log('过滤后的账户:', this.accounts)
			} catch (error) {
				console.error('加载账户失败:', error)
				
				// 如果是401错误，说明token无效
				if (error.message.includes('401') || error.message.includes('登录已过期')) {
					console.log('Token已过期，跳转登录页面')
					uni.reLaunch({
						url: '/pages/login/login'
					})
					return
				}
				
				uni.showToast({
					title: '加载失败: ' + error.message,
					icon: 'none',
					duration: 3000
				})
			} finally {
				this.loading = false
			}
		},
			async loadTotalBalance() {
				try {
					this.totalBalance = await accountAPI.getTotalBalance()
				} catch (error) {
					console.error('加载总资产失败:', error)
				}
			},
			getAccountTypeText(type) {
				const typeItem = this.accountTypes.find(t => t.value === type)
				return typeItem ? typeItem.name : type
			},
			showAddModal() {
				this.isEdit = false
				this.editAccountId = null
				this.resetForm()
				this.modalVisible = true
			},
			editAccount(account) {
				this.isEdit = true
				this.editAccountId = account.id
				this.formData = {
					name: account.name,
					accountType: account.accountType,
					icon: account.icon,
					balance: account.currentBalance.toString(),
					description: account.description || '',
					includeInTotal: account.includeInTotal
				}
				this.modalVisible = true
			},
			hideModal() {
				this.modalVisible = false
				this.resetForm()
			},
			resetForm() {
				this.formData = {
					name: '',
					accountType: 'CASH',
					icon: '💰',
					balance: '',
					description: '',
					includeInTotal: true
				}
			},
			selectAccountType(type) {
				this.formData.accountType = type
				// 自动设置对应的图标
				const typeItem = this.accountTypes.find(t => t.value === type)
				if (typeItem) {
					this.formData.icon = typeItem.icon
				}
			},
			selectIcon(icon) {
				this.formData.icon = icon
			},
			toggleIncludeInTotal() {
				this.formData.includeInTotal = !this.formData.includeInTotal
			},
			async saveAccount() {
				if (!this.formData.name.trim()) {
					uni.showToast({
						title: '请输入账户名称',
						icon: 'none'
					})
					return
				}
				
				try {
					const accountData = {
						name: this.formData.name.trim(),
						accountType: this.formData.accountType,
						icon: this.formData.icon,
						description: this.formData.description.trim(),
						includeInTotal: this.formData.includeInTotal,
						initialBalance: parseFloat(this.formData.balance) || 0,
						currentBalance: parseFloat(this.formData.balance) || 0
					}
					
					if (this.isEdit) {
						await accountAPI.update(this.editAccountId, accountData)
						uni.showToast({
							title: '更新成功',
							icon: 'success'
						})
					} else {
						await accountAPI.create(accountData)
						uni.showToast({
							title: '创建成功',
							icon: 'success'
						})
					}
					
					this.hideModal()
					this.loadAccounts()
					this.loadTotalBalance()
					
				} catch (error) {
					console.error('保存账户失败:', error)
					uni.showToast({
						title: '保存失败: ' + error.message,
						icon: 'none'
					})
				}
			},
			viewAccountHistory(account) {
				console.log('查看账户历史记录:', account)
				uni.navigateTo({
					url: `/pages/account-history/account-history?accountId=${account.id}&accountName=${encodeURIComponent(account.name)}`
				})
			},
			confirmDelete(account) {
				uni.showModal({
					title: '确认删除',
					content: `确定要删除账户"${account.name}"吗？此操作不可恢复。`,
					confirmText: '删除',
					confirmColor: '#FF6B6B',
					success: (res) => {
						if (res.confirm) {
							this.deleteAccount(account.id)
						}
					}
				})
			},
			async deleteAccount(accountId) {
				try {
					await accountAPI.delete(accountId)
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					})
					this.loadAccounts()
					this.loadTotalBalance()
				} catch (error) {
					console.error('删除账户失败:', error)
					uni.showToast({
						title: '删除失败: ' + error.message,
						icon: 'none'
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/uni.scss';
	
	.page-container {
		width: 100%;
		height: 100vh;
	}
	
	.container {
		background: $cute-gradient-bg;
		min-height: 100vh;
		padding-bottom: 120rpx;
		padding-top: calc(var(--status-bar-height, 44px) + 88rpx);
	}
	
	/* 账户列表 */
	.accounts-section {
		margin: 20rpx;
		background: $cute-bg-secondary;
		border-radius: $cute-border-radius;
		box-shadow: $cute-card-shadow;
		border: 2rpx solid $cute-border;
	}
	
	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 2rpx solid $cute-divider;
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: $cute-text-primary;
	}
	
	.add-account-btn {
		display: flex;
		align-items: center;
		background: $cute-gradient-primary;
		padding: 15rpx 25rpx;
		border-radius: $cute-border-radius;
		transition: $cute-transition;
		
		&:active {
			transform: scale(0.95);
		}
	}
	
	.add-icon {
		font-size: 24rpx;
		color: $cute-text-inverse;
		margin-right: 10rpx;
		font-weight: bold;
	}
	
	.add-text {
		font-size: 24rpx;
		color: $cute-text-inverse;
		font-weight: 500;
	}
	
	.accounts-list {
		padding: 0 30rpx;
	}
	
	.account-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 0;
		border-bottom: 2rpx solid $cute-divider;
		transition: $cute-transition;
		
		&:last-child {
			border-bottom: none;
		}
		
		&:active {
			background: $cute-bg-tertiary;
			margin: 0 -30rpx;
			padding: 30rpx;
			border-radius: $cute-border-radius;
		}
	}
	
	.account-info {
		display: flex;
		align-items: center;
		flex: 1;
	}
	
	.account-icon {
		font-size: 40rpx;
		margin-right: 20rpx;
	}
	
	.account-details {
		display: flex;
		flex-direction: column;
	}
	
	.account-name {
		font-size: 30rpx;
		color: $cute-text-primary;
		font-weight: 600;
		margin-bottom: 5rpx;
	}
	
	.account-type {
		font-size: 24rpx;
		color: $cute-text-secondary;
	}
	
	.account-balance {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
	}
	
	.balance-amount {
		font-size: 28rpx;
		color: $cute-text-primary;
		font-weight: bold;
		margin-bottom: 10rpx;
	}
	
	.account-actions {
		display: flex;
		gap: 10rpx;
	}
	
	.action-btn {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: $cute-transition;
		
		&.history {
			background: linear-gradient(135deg, #2196F3, #64B5F6);
		}
		
		&.edit {
			background: $cute-gradient-accent;
		}
		
		&.delete {
			background: linear-gradient(135deg, #FF6B6B, #FF8E8E);
		}
		
		&:active {
			transform: scale(0.9);
		}
	}
	
	.action-icon {
		font-size: 24rpx;
	}
	
	/* 空状态 */
	.empty-state {
		padding: 80rpx 40rpx;
		text-align: center;
	}
	
	.empty-icon {
		font-size: 80rpx;
		margin-bottom: 20rpx;
	}
	
	.empty-text {
		display: block;
		font-size: 32rpx;
		color: $cute-text-primary;
		font-weight: bold;
		margin-bottom: 10rpx;
	}
	
	.empty-desc {
		font-size: 26rpx;
		color: $cute-text-secondary;
	}
	
	/* 总资产统计 */
	.summary-section {
		margin: 20rpx;
		background: $cute-gradient-primary;
		border-radius: $cute-border-radius;
		padding: 30rpx;
		box-shadow: $cute-card-shadow;
	}
	
	.summary-item {
		text-align: center;
	}
	
	.summary-label {
		display: block;
		font-size: 28rpx;
		color: $cute-text-inverse;
		margin-bottom: 10rpx;
	}
	
	.summary-amount {
		display: block;
		font-size: 48rpx;
		color: $cute-text-inverse;
		font-weight: bold;
	}
	
	/* 模态框样式 */
	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 10000;
	}
	
	.modal-content {
		width: 90%;
		max-height: 80vh;
		background: $cute-bg-primary;
		border-radius: $cute-border-radius;
		box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);
		overflow: hidden;
	}
	
	.modal-header {
		background: $cute-gradient-primary;
		padding: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		color: $cute-text-inverse;
	}
	
	.modal-title {
		font-size: 32rpx;
		font-weight: bold;
	}
	
	.close-btn {
		width: 60rpx;
		height: 60rpx;
		background: rgba(255, 255, 255, 0.2);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		
		&:active {
			transform: scale(0.9);
		}
	}
	
	.close-icon {
		font-size: 36rpx;
		font-weight: bold;
	}
	
	.modal-body {
		padding: 30rpx;
		max-height: 50vh;
		overflow-y: auto;
	}
	
	.form-item {
		margin-bottom: 30rpx;
	}
	
	.form-label {
		display: block;
		font-size: 28rpx;
		color: $cute-text-primary;
		font-weight: 600;
		margin-bottom: 15rpx;
	}
	
	.form-input {
		width: 100%;
		height: 80rpx;
		border: 2rpx solid $cute-border;
		border-radius: $cute-border-radius;
		padding: 0 20rpx;
		font-size: 28rpx;
		background: $cute-bg-secondary;
		color: $cute-text-primary;
		box-sizing: border-box;
		
		&:focus {
			border-color: $cute-primary;
		}
	}
	
	.account-types {
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
	}
	
	.type-option {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20rpx;
		border: 2rpx solid $cute-border;
		border-radius: $cute-border-radius;
		background: $cute-bg-secondary;
		transition: $cute-transition;
		min-width: 120rpx;
		
		&.active {
			border-color: $cute-primary;
			background: $cute-gradient-primary;
			color: $cute-text-inverse;
		}
		
		&:active {
			transform: scale(0.95);
		}
	}
	
	.type-icon {
		font-size: 32rpx;
		margin-bottom: 8rpx;
	}
	
	.type-name {
		font-size: 24rpx;
		font-weight: 500;
	}
	
	.icon-selector {
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
	}
	
	.icon-option {
		width: 80rpx;
		height: 80rpx;
		border: 2rpx solid $cute-border;
		border-radius: $cute-border-radius;
		background: $cute-bg-secondary;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: $cute-transition;
		
		&.active {
			border-color: $cute-primary;
			background: $cute-gradient-primary;
		}
		
		&:active {
			transform: scale(0.9);
		}
	}
	
	.icon-text {
		font-size: 32rpx;
	}
	
	.checkbox-item {
		display: flex;
		align-items: center;
	}
	
	.checkbox {
		width: 40rpx;
		height: 40rpx;
		border: 2rpx solid $cute-border;
		border-radius: 8rpx;
		background: $cute-bg-secondary;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 15rpx;
		transition: $cute-transition;
		
		&.checked {
			background: $cute-gradient-primary;
			border-color: $cute-primary;
		}
	}
	
	.check-icon {
		color: $cute-text-inverse;
		font-size: 24rpx;
		font-weight: bold;
	}
	
	.checkbox-label {
		font-size: 28rpx;
		color: $cute-text-primary;
	}
	
	.modal-footer {
		display: flex;
		padding: 30rpx;
		gap: 20rpx;
		border-top: 2rpx solid $cute-divider;
	}
	
	.btn-cancel,
	.btn-save {
		flex: 1;
		height: 80rpx;
		border-radius: $cute-border-radius;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		font-weight: 600;
		transition: $cute-transition;
		
		&:active {
			transform: scale(0.95);
		}
	}
	
	.btn-cancel {
		background: $cute-bg-tertiary;
		color: $cute-text-secondary;
		border: 2rpx solid $cute-border;
	}
	
	.btn-save {
		background: $cute-gradient-primary;
		color: $cute-text-inverse;
	}
</style>
